from datetime import datetime, timedelta, time as dt_time
import pytz
import holidays
import logging
import re

logger = logging.getLogger(__name__)


class FrequencyChecker:
    def __init__(self, rule):
        self.rule = rule
        self.now = datetime.now(pytz.timezone(rule.timezone or 'Asia/Shanghai'))
        self.last_trigger = rule.last_trigger_time
        self.last_trigger = (
            rule.last_trigger_time.replace(tzinfo=pytz.timezone(rule.timezone or 'Asia/Shanghai'))
            if rule.last_trigger_time and rule.last_trigger_time.tzinfo is None
            else rule.last_trigger_time
        )

        # 初始化节假日库（需要安装 holidays 包）
        self.holidays = holidays.CountryHoliday('CN')  # 中国节假日

    def should_trigger(self):
        """判断是否应该触发预警"""
        # 如果从未触发过，应该执行
        if not self.last_trigger:
            return True

        # 检查是否在非工作日跳过
        if self.should_skip():
            logger.debug(f"规则 {self.rule.rule_name} 在非工作日跳过")
            return False

        # 根据频率类型判断
        if self.rule.frequency.endswith('m'):
            return self.check_minute_frequency()
        elif self.rule.frequency.endswith('h'):
            return self.check_hour_frequency()
        elif self.rule.frequency.endswith('d'):
            return self.check_day_frequency()
        elif self.rule.frequency.startswith('daily'):
            return self.check_daily_frequency()

        # 默认每小时执行
        return (self.now - self.last_trigger) >= timedelta(hours=1)

    def should_skip(self):
        """检查是否应该跳过执行（周末/节假日）"""
        # 检查是否跳过周末（周六或周日）
        if self.rule.skip_weekends and self.now.weekday() in [5, 6]:
            return True

        # 检查是否跳过节假日
        if self.rule.skip_holidays and self.now.date() in self.holidays:
            return True

        return False

    def check_minute_frequency(self):
        """检查分钟级频率"""
        minutes = int(self.rule.frequency[:-1])
        interval = timedelta(minutes=minutes)
        return (self.now - self.last_trigger) >= interval

    def check_hour_frequency(self):
        """检查小时级频率"""
        hours = int(self.rule.frequency[:-1])
        interval = timedelta(hours=hours)
        return (self.now - self.last_trigger) >= interval

    def check_day_frequency(self):
        """检查天级频率"""
        days = int(self.rule.frequency[:-1])
        interval = timedelta(days=days)
        return (self.now - self.last_trigger) >= interval

    def check_daily_frequency(self):
        """检查每日固定时间频率"""
        # 解析时间
        time_str = self.rule.frequency.split(':')[1] + ':' + self.rule.frequency.split(':')[2]
        hour, minute = map(int, time_str.split(':'))

        # 获取今天的执行时间
        today_execution = self.now.replace(
            hour=hour,
            minute=minute,
            second=0,
            microsecond=0
        )

        # 如果当前时间已经过了今天的执行时间
        # 且上次执行时间在今天执行时间之前
        return (self.now >= today_execution and
                (self.last_trigger is None or
                 self.last_trigger < today_execution))